﻿namespace Compass.Maui.Services;
//需要配置明文流量
//https://learn.microsoft.com/zh-cn/training/modules/consume-rest-services-maui/4-use-platform-specific-features
/// <summary>
/// 包装RestSharp类
/// </summary>
public interface IHttpRestClient
{
    Task<ApiResponse<T>> ExecuteAsync<T>(BaseRequest baseRequest);
}
public class HttpRestClient : IHttpRestClient
{
    //todo:检查局域网是否可用，不可用则弹窗警告
    private const string ApiUrl = "http://10.9.18.31/api";
    private readonly IRestClient _client;
    private readonly IPreferenceService _preferenceService;
    public HttpRestClient(IPreferenceService preferenceService)
    {
        var options = new RestClientOptions(ApiUrl)
        {
            MaxTimeout = 30000, //配置RestClient的timeout option,30秒
            ThrowOnAnyError = true//抛出异常
        };
        _client=new RestClient(options);
        _preferenceService = preferenceService;
    }
    public async Task<ApiResponse<T>> ExecuteAsync<T>(BaseRequest baseRequest)
    {
        var request = new RestRequest(baseRequest.Route, baseRequest.Method);
        //获取token，给请求添加token
        var token = _preferenceService.Get(Consts.Token, string.Empty);
        if (!string.IsNullOrEmpty(token))
        {
            request.AddOrUpdateHeader("Authorization", $"Bearer {token.Replace("\"", "")}");
        }
        //传递的参数，必须使用Newtonsoft.Json，不能使用微软自带Json
        //Get方法不要带body，使用url传参数，否则在android设备上报错NotFound
        if (baseRequest.Param is not null)
        {
            request.AddHeader("Content-Type", baseRequest.ContentType);
            request.AddJsonBody(baseRequest.Param);
        }


        var response = await _client.ExecuteAsync(request);

        if (response.StatusCode == HttpStatusCode.OK)
        {
            return JsonConvert.DeserializeObject<ApiResponse<T>>(response.Content!)!;
        }
        return new ApiResponse<T> { Status = false, Message = response.ErrorMessage };

    }
}